import { Menu } from '../../types';
import { MenuRepository } from '../../repositories/system/MenuRepository';
import { HttpError } from '../../exceptions/HttpError';
export class MenuService {
  private menuRepository: MenuRepository;

  constructor() {
    this.menuRepository = new MenuRepository();
  }



  // // 获取所有菜单
  async getAllMenus(): Promise<Menu[]> {
    try {
      return await this.menuRepository.findAll();
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`获取菜单列表失败: ${error.message}`);
    }
  }

  // // 根据ID获取用户
  async getMenuById(id: string): Promise<Menu | null> {
    try {
      return await this.menuRepository.findById(id);
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`获取菜单信息失败: ${error.message}`);
    }
  }

  // 创建用户
  async createMenu(menuData: Partial<Menu>): Promise<Menu> {
    try {
      return await this.menuRepository.create(menuData);
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`创建菜单失败: ${error.message}`);
    }
  }

  // 更新菜单
  async updateMenu(id: string, menuData: Partial<Menu>): Promise<Menu | null> {
    try {
      return await this.menuRepository.update(id, menuData);
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`更新菜单失败: ${error.message}`);
    }
  }

  // 删除菜单
  async deleteMenu(id: string): Promise<boolean> {
    try {
      return await this.menuRepository.delete(id);
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`删除菜单失败: ${error.message}`);
    }
  }



  // 获取菜单数量
  async getMenuCount(): Promise<number> {
    try {
      return await this.menuRepository.count();
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`统计菜单数量失败: ${error.message}`);
    }
  }

  // 分页查询菜单
  async getMenusWithPagination(page: number = 1, limit: number = 10): Promise<{ list: Menu[], total: number, pages: number }> {
    try {
      return await this.menuRepository.findWithPagination(page, limit);
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`分页查询菜单失败: ${error.message}`);
    }
  }
}